﻿using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Globalization;
using System.IO;
using System.IO.IsolatedStorage;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Windows;
using System.Windows.Navigation;
using Windows.Storage;
using Windows.System;
using BlogApp.Data;
using BlogApp.Data.Models;
using BlogApp.WP8.Resources;
using BlogApp.WP8.Utils;
using BlogApp.WP8.ViewModel;
using HtmlAgilityPack;
using Microsoft.Phone.Controls;
using Microsoft.Phone.Shell;
using Microsoft.Phone.Tasks;
using Microsoft.Practices.ServiceLocation;
using Newtonsoft.Json;

namespace BlogApp.WP8.View
{
    public partial class PostDetailPage : PhoneApplicationPage
    {
        private PostViewModel _vm;
        public PostDetailPage()
        {
            InitializeComponent();
            _vm = (PostViewModel)DataContext;
        }

        protected override async void OnNavigatedTo(NavigationEventArgs e)
        {
            buildAppBar();
            ((ApplicationBarMenuItem)ApplicationBar.MenuItems[2]).IsEnabled = !_vm.SelectedBlogPost.IsOffline;


            // save content into a tempfile as it wont load images for offline posts when using NavigateToString
            var document = new HtmlDocument();
            string comments = _vm.SelectedBlogPost.Comments.Any() ? Statics.COMMENT_HEADER_TEMPLATE : string.Empty;

            foreach (var comment in _vm.SelectedBlogPost.Comments)
            {
                try
                {

                    var result = await JsonConvert.DeserializeObjectAsync<Comment>(comment.ToString());

                    if (result != null)
                    {
                        var dateTime = DateTime.Parse(result.Date, new CultureInfo("de-DE"));
                        var date = dateTime.ToString("dd. MMMM yyyy");
                        var time = dateTime.ToString("HH:mm");

                        var headerString = string.Format("{0} sagte am {1} um {2}", result.Name, date, time);

                        comments += string.Format(Statics.COMMENT_TEMPLATE, App.Current.Resources["AccentColor"].ToString().Substring(3), headerString, result.Content);

                    }
                }
                catch (Exception exception)
                {
                    Console.WriteLine(exception);
                }


            }

            var content = string.Format(Statics.CONTENT_TEMPLATE, App.Current.Resources["BackgroundColor"].ToString().Substring(3), App.Current.Resources["AccentColor"].ToString().Substring(3), App.Current.Resources["TeaserTextColor"].ToString().Substring(3), _vm.SelectedBlogPost.Content + comments);

            document.LoadHtml(content);



            #region Convert Youtube-Links to embedded vidos
            // get all links

            var paragraphCollection = document.DocumentNode.Descendants("p");
            foreach (var htmlNode in paragraphCollection.ToArray())
            {
                HtmlNode frame = htmlNode.ChildNodes.FirstOrDefault(i => i.Name == "iframe");
                if (frame != null)
                {
                    var src = frame.Attributes.First(a => a.Name == "src");


                    var newVideoNode = string.Format("<a href=\"{0}\"><img src=\"/Assets/youtubeLogo.jpg\" width=\"600\" /></a>", src.Value);
                    htmlNode.InnerHtml = newVideoNode;
                }
            }


            #endregion


            var _localStorage = ApplicationData.Current.LocalFolder;

            var storageFileIsolated = await _localStorage.CreateFileAsync(Statics.TEMPFILE_NAME, CreationCollisionOption.ReplaceExisting);
            using (Stream writeStream = await storageFileIsolated.OpenStreamForWriteAsync())
            {
                document.Save(writeStream, Encoding.UTF8);
                writeStream.Flush();
                writeStream.Close();
                writeStream.Dispose();
            }


            webBrowser.Navigate(new Uri(Statics.TEMPFILE_NAME, UriKind.Relative));

            webBrowser.Navigating += WebBrowserOnNavigating;
            base.OnNavigatedTo(e);
        }

        protected override void OnNavigatingFrom(NavigatingCancelEventArgs e)
        {
            webBrowser.Navigating -= WebBrowserOnNavigating;
            base.OnNavigatingFrom(e);
        }

        private void WebBrowserOnNavigating(object sender, NavigatingEventArgs e)
        {
            if (e.Uri.ToString() != Statics.TEMPFILE_NAME)
            {
                Launcher.LaunchUriAsync(e.Uri);
                e.Cancel = true;
            }
        }


        private void buildAppBar()
        {
            ((ApplicationBarMenuItem)ApplicationBar.MenuItems[0]).Text = AppResources.AppBarMenuItemComment;
            ((ApplicationBarMenuItem)ApplicationBar.MenuItems[1]).Text = AppResources.AppBarMenuItemOpenBrowserText;
            ((ApplicationBarMenuItem)ApplicationBar.MenuItems[2]).Text = AppResources.AppBarMenuItemSaveOfflineText;
            ((ApplicationBarMenuItem)ApplicationBar.MenuItems[3]).Text = AppResources.AppBarMenuItemShareLinkText;
            ((ApplicationBarMenuItem)ApplicationBar.MenuItems[4]).Text = AppResources.AppBarMenuItemSendLinkText;
        }

        private void saveOfflineMenuItem_Click(object sender, EventArgs e)
        {
            _vm.SavePostOfflineCommand.Execute(_vm.SelectedBlogPost);
            MessageBox.Show(AppResources.MessageBoxSaveOfflineConfirmation, string.Empty, MessageBoxButton.OK);
            ServiceLocator.Current.GetInstance<MainViewModel>().LoadOfflinePosts.Execute(null);

            ((ApplicationBarMenuItem)ApplicationBar.MenuItems[2]).IsEnabled = !_vm.SelectedBlogPost.IsOffline;
        }

        private void openInBrowserMenuItem_Click(object sender, EventArgs e)
        {
            Launcher.LaunchUriAsync(new Uri(_vm.SelectedBlogPost.Url));
        }

        private void shareLinkMenuItem_Click(object sender, EventArgs e)
        {
            var shareLinkTask = new ShareLinkTask()
            {
                Title = _vm.SelectedBlogPost.TitlePlain.HtmlDecode(),
                LinkUri = new Uri(_vm.SelectedBlogPost.Url, UriKind.Absolute),
                Message = string.Format("{0}{1}{2}", _vm.SelectedBlogPost.Excerpt.HtmlDecode(), Environment.NewLine + Environment.NewLine, AppResources.ShareTextSubline)
            };

            shareLinkTask.Show();
        }

        private void sendLinkMenuItem_Click(object sender, EventArgs e)
        {
            var emailComposeTask = new EmailComposeTask()
            {
                Subject = _vm.SelectedBlogPost.Title.HtmlDecode(),
                Body = string.Format("{0}{1}{2}{3}{4}", _vm.SelectedBlogPost.Excerpt.HtmlDecode(), Environment.NewLine + Environment.NewLine, _vm.SelectedBlogPost.Url, Environment.NewLine, AppResources.ShareTextSubline)
            };

            emailComposeTask.Show();
        }

        private void AppBarMenuItemComment_Click(object sender, EventArgs e)
        {
            ServiceLocator.Current.GetInstance<MainViewModel>().NavigateCommand.Execute(String.Format("/View/CommentPage.xaml?blogid={0}", _vm.SelectedBlogPost.Id));
        }
    }
}